<template>
  <div v-loading="loading">
    <el-card>
      <div slot="header" class="clearfix text-left">
        <el-col :span="23">
          <span class="title-icon">打单平台</span>
        </el-col>
      </div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="逐个获取" name="first">
          <el-row style="margin-top: 30px;margin-bottom: 30px">
            <el-col :span="1">
              <span>运单号:</span>
            </el-col>
            <el-col :span="6">
              <el-input
                size="large"
                :rows="5"
                v-model="sigleOrderNo"
                type="textarea"
                placeholder="请输入运单号"
              ></el-input>
            </el-col>
            <el-col :span="10" style="margin-left: 10px;">
              <el-button size="mini" type="primary" @click="sigleQueryOrder"
                >查询</el-button
              >
            </el-col>
            <el-col :span="1">
              <span>选择帐号:</span>
            </el-col>
            <el-col :span="3">
              <el-select
                v-model="labelAccountValue1"
                placeholder="请选择"
                size="mini"
              >
                <el-option
                  v-for="(item, value) in labelAccountSource"
                  :key="value"
                  :label="item"
                  :value="value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2" style="margin-left: 10px;">
              <el-button
                size="mini"
                type="primary"
                @click="sigleTrackLabelSubmit"
                >提交</el-button
              >
            </el-col>
          </el-row>
          <div v-if="boo" style="margin-top: 30px;margin-bottom: 30px">
            <div>
              <el-table :data="cuList" style="width: 100%" size="mini">
                <el-table-column prop="orderNo" label="单号"> </el-table-column>
                <el-table-column prop="countryName" label="目的国家">
                </el-table-column>
                <el-table-column prop="provinceName" label="国内省">
                </el-table-column>
                <el-table-column prop="fbaCode" label="FBACODE">
                </el-table-column>
                <el-table-column
                  prop="print"
                  label="已打件数"
                ></el-table-column>
                <el-table-column prop="paddingSize" label="打单中件数">
                </el-table-column>
                <el-table-column prop="remain" label="未打件数">
                </el-table-column>
                <el-table-column prop="tatal" label="总件数"></el-table-column>
                <el-table-column prop="printNum" label="本次打印件数">
                  <!-- v-model="scope.row['printNum']" -->
                  <template slot-scope="scope">
                    <el-input
                      size="mini"
                      v-model.number="scope.row.printNum"
                      @input="numberCheck"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="
                        handleDelete(scope.row.id, scope.row, scope.$index)
                      "
                      >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="批量获取" name="second">
          <el-row style="margin-top: 30px;margin-bottom: 30px">
            <el-col :span="1">
              <span>运单号:</span>
            </el-col>
            <el-col :span="6">
              <el-input
                size="large"
                :rows="5"
                v-model="batchOrderNo"
                type="textarea"
                placeholder="请输入运单号,多个换行隔开"
              ></el-input>
            </el-col>
            <el-col :span="10" style="margin-left: 10px;">
              <el-button size="mini" type="primary" @click="batchQueryOrder"
                >查询</el-button
              >
            </el-col>
            <el-col :span="1">
              <span>选择帐号:</span>
            </el-col>
            <el-col :span="3">
              <el-select
                v-model="labelAccountValue2"
                placeholder="请选择"
                size="mini"
              >
                <el-option
                  v-for="(item, value) in labelAccountSource"
                  :key="value"
                  :label="item"
                  :value="value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2" style="margin-left: 10px;">
              <el-button
                size="mini"
                type="primary"
                @click="batchTrackLabelSubmit"
                >提交</el-button
              >
            </el-col>
          </el-row>

          <div>
            <el-table :data="orderPrintList" style="width: 100%" size="mini">
              <el-table-column prop="orderNo" label="单号"> </el-table-column>
              <el-table-column prop="countryName" label="目的国家">
              </el-table-column>
              <el-table-column prop="provinceName" label="国内省">
              </el-table-column>
              <el-table-column prop="fbaCode" label="FBACODE">
              </el-table-column>
              <el-table-column prop="tatal" label="总件数"> </el-table-column>
              <el-table-column prop="paddingSize" label="打单中件数">
              </el-table-column>
              <el-table-column prop="remain" label="未打件数">
              </el-table-column>
              <el-table-column prop="print" label="已打件数"> </el-table-column>
              <el-table-column prop="printNum" label="本次打印件数">
                <template slot-scope="scope">
                  <el-input
                    size="mini"
                    v-model.number="scope.row.printNum"
                    @input="numberCheck"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="accountName" label="帐号">
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.row.id, scope.row, scope.$index)"
                    >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="批量获取GreenBox标签" name="third">
          <el-row style="margin-top: 30px;margin-bottom: 30px">
            <el-input size="mini" type="hidden" v-model="printName"></el-input>
            <el-col :span="1">
              <span>运单号:</span>
            </el-col>
            <el-col :span="6">
              <el-input
                size="large"
                :rows="5"
                v-model="printOrderNo"
                type="textarea"
                placeholder="请输入订单号,换行隔开"
              ></el-input>
            </el-col>
            <el-col :span="4" style="margin-left: 10px;">
              <el-button size="mini" type="primary" @click="printGreenBoxLabel"
                >打印</el-button
              >
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";

export default {
  components: {},
  props: [],
  data() {
    return {
      activeName: "first",
      sigleOrderNo: "",
      batchOrderNo: "",
      loading: false,
      cuList: [],
      labelAccountSource: [],
      orderPrintList: [],
      boo: true,
      labelAccountValue1: "",
      labelAccountValue2: "",
      printName: "",
      printOrderNo: ""
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.initLabelAccountSource();
    this.initPrinterName();
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    numberCheck(val) {
      console.log(val);
    },
    handleDelete(id, row, i) {
      ajax("delete", { id: id }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.orderPrintList.splice(i, 1);
          } else {
            this.$message.error("删除失败" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    sigleQueryOrder() {
      this.loading = true;
      if (!this.sigleOrderNo) {
        this.$message.error("请录入订单号");
      }
      var waybillArray = this.sigleOrderNo.split("\n");
      this.commonQueryOrder(waybillArray, 0);
    },
    batchQueryOrder() {
      this.loading = true;
      if (!this.batchOrderNo) {
        this.$message.error("请录入订单号");
        return;
      }
      if (
        this.batchOrderNo.indexOf(",") > -1 ||
        this.batchOrderNo.indexOf("，") > -1
      ) {
        this.$message.error("多个订单号换行隔开,不含逗号");
        return;
      }
      var waybillArray = this.batchOrderNo.split("\n");
      this.commonQueryOrder(waybillArray, 1);
    },
    commonQueryOrder(waybillArray, type) {
      var reg = /^[0-9a-zA-Z]+$/; // 验证0-9的任意数字最少出现1次。
      var waybillList = new Array();
      for (var n = 0; n < waybillArray.length; n++) {
        if (waybillArray[n]) {
          if (reg.test(waybillArray[n])) {
            if (waybillList.indexOf(waybillArray[n]) > -1) {
              this.$message.error({
                msg: "订单号【" + waybillArray[n] + "】重复"
              });
              return;
            } else {
              waybillList.push(waybillArray[n]);
            }
          } else {
            this.$message.error("订单号输入有误");
            return;
          }
        }
      }
      ajax("queryWaybills", { waybillList: waybillList, type: type }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            if (type == 0) {
              this.cuList = res.data;
            } else if (type == 1) {
              if (res.data) {
                for (var str of res.data) {
                  str.printNum = str.remain;
                }
              }
              this.orderPrintList = res.data;
            }
          } else {
            this.$message.error("操作失败" + res.message);
          }
          this.loading = false;
        },
        error => {
          console.log(error);
        }
      );
    },
    initLabelAccountSource() {
      ajax("initLabelAccountSource", {}).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.labelAccountSource = res.data;
        } else {
          this.$message.error("操作失败" + res.message);
        }
      });
    },
    initPrinterName() {
      ajax("initPrinterName", {}).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.printName = res.data;
          } else {
            this.$message.error("操作失败" + res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    sigleTrackLabelSubmit() {
      if (this.cuList.length == 0) {
        this.$message.error("请先给订单录入打印件数");
        return;
      }
      var maxNumFlag = true;
      var flag = true;
      for (var cu of this.cuList) {
        if (cu.printNum) {
          if (!this.isInteger(cu.printNum)) {
            this.$message.error("打印件数只能录入大于0的整数");
            cu.printNum = "";
            flag = false;
            return;
          }
          if (parseInt(cu.printNum) > parseInt(cu.remain)) {
            this.$message.error("打印件数超过了可打印件数");
            maxNumFlag = false;
          }
        } else {
          this.$message.error("请输入打印数量");
          flag = false;
          return;
        }
      }
      if (!this.labelAccountValue1) {
        this.$message.error("请输入账号");
        return;
      }
      if (!flag) {
        return false;
      }
      const minWeight = 68;
      var isWarnWeight = false;
      if (this.labelAccountValue1 == "US-UPS-GFP-9774R5-CA") {
        let checkArray = new Array();
        checkArray.push({
          totalOrderNo: this.cu.orderNo,
          totalSize: this.number
        });
        var checkData = JSON.stringify(checkArray); //如果传输重量小于等于68则提示
        ajax("checkOrderMinWeight", {
          jsonData: checkData,
          minWeight: minWeight
        }).then(
          res => {
            if (res.code == 200) {
              isWarnWeight = true;
            } else {
              this.$message.error("重量检测出现异常" + res.message);
              return;
            }
          },
          error => {
            console.log(error);
          }
        );
      } else if (
        this.labelAccountValue1 !== null &&
        this.labelAccountValue1.indexOf("DHL") != -1
      ) {
        // DHL 一次只能打25件
        if (this.number > 30) {
          this.$message.warning(
            "DHL一次只允许打印30件，系统将会为你分批请求，如有异常请及时联系IT"
          );
          // return;
        }
      }
      if (isWarnWeight) {
        this.$confirm("单号重量<=68 是否确认用此账号打单？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(() => {
          if (!maxNumFlag) {
            this.$confirm("单号重量<=68 是否确认用此账号打单？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消"
            }).then(() => {
              this.trackLabel();
            });
          } else {
            this.trackLabel();
          }
        });
      } else {
        if (!maxNumFlag) {
          this.$confirm("单号重量<=68 是否确认用此账号打单？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消"
          }).then(() => {
            this.trackLabel();
          });
        } else {
          this.trackLabel();
        }
      }
    },

    trackLabel() {
      this.loading = true;
      ajax("singleTrackPrintlabel", {
        shippingAccountName: this.labelAccountValue1,
        orderPrintList: this.cuList
      }).then(
        res => {
          if (res.code == 200) {
            this.$message.success("已推送，请前往追踪标签信息页面查看结果");
            this.timeout = setTimeout(() => {
              window.location.reload(true);
            }, 3000 * Math.random());
          } else {
            this.$message.error("推送失败" + res.message);
            return;
          }
          this.loading = false;
        },
        error => {
          this.loading = false;
          console.log(error);
        }
      );
    },
    isInteger(obj) {
      if (isNaN(obj) || obj % 1 != 0 || parseInt(obj) <= 0) {
        return false;
      }
      return true;
    },
    batchTrackLabelSubmit() {
      if (!this.labelAccountValue2) {
        this.$message.error("请先选择帐号");
        return;
      }
      if (this.orderPrintList.length == 0) {
        $("#batchTrackLabel").removeAttr("disabled");
        this.$message.error("请先给订单录入打印件数");
        return;
      }
      var flag = true;
      var maxNumFlag = true;
      var checkArray = new Array();
      for (var i = 0; i < this.orderPrintList.length; i++) {
        var orderPrint = this.orderPrintList[i];
        if (orderPrint.printNum) {
          if (!this.isInteger(orderPrint.printNum)) {
            this.$message.error(
              orderPrint.orderNo + "：打印件数只能录入大于0的整数"
            );
            flag = false;
            return false;
          }
          if (parseInt(orderPrint.printNum) > parseInt(orderPrint.total)) {
            this.$message.error(orderPrint.orderNo + "：打印件数超过总件数");
            flag = false;
            return false;
          }
          if (parseInt(orderPrint.print) > parseInt(orderPrint.remain)) {
            this.$message.error(
              "订单：" +
                orderPrint.orderNo +
                " &nbsp;打印件数超过了可打印件数" +
                "\r\n"
            );
            maxNumFlag = false;
          }
          checkArray.push({
            totalOrderNo: orderPrint.orderNo,
            totalSize: orderPrint.print
          });
        }
      }
      if (!flag) {
        return false;
      }
      var data = JSON.stringify(this.orderPrintList);
      console.log(data);
      var minWeight = 68;
      var isWarnWeight = false;
      if (this.labelAccountValue2 == "US-UPS-GFP-9774R5-CA") {
        //如果传输重量小于等于68则提示
        var checkData = JSON.stringify(checkArray);
        ajax("checkOrderMinWeight", {
          jsonData: checkData,
          minWeight: minWeight
        }).then(
          res => {
            if (res.code == 200) {
              isWarnWeight = true;
            } else {
              this.$message.error("重量检测出现异常" + res.message);
              return;
            }
          },
          error => {
            console.log(error);
          }
        );
      }
      if (isWarnWeight) {
        this.$confirm("单号重量<=68 是否确认用此账号打单？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (!maxNumFlag) {
            this.$confirm("单号重量<=68 是否确认用此账号打单？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.trackLabel2();
            });
          } else {
            this.trackLabel2();
          }
        });
      } else {
        if (!maxNumFlag) {
          this.$confirm("单号重量<=68 是否确认用此账号打单？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.trackLabel2();
          });
        } else {
          this.trackLabel2();
        }
      }
    },
    trackLabel2() {
      this.loading = true;
      let headers = {};
      headers["YG-UNIQUE-KEY"] = "trackPrintlabel_" + new Date().getTime();
      let attrs = { headers: headers };

      ajax(
        "trackPrintlabel",
        {
          shippingAccountName: this.labelAccountValue2,
          orderPrintList: this.orderPrintList
        },
        attrs
      ).then(
        res => {
          if (res.code == 200) {
            this.$message.success("已推送，请前往追踪标签信息页面查看结果");
            this.timeout = setTimeout(() => {
              window.location.reload();
            }, 3000 * Math.random());
          } else {
            this.$message.error("打单失败" + res.message);
            return;
          }
          this.loading = false;
        },
        error => {
          console.log(error);
          this.loading = false;
        }
      );
    },
    /**
     * 打印绿盒标签
     * @returns
     */
    printGreenBoxLabel() {
      if (!this.printName) {
        this.$message.error("当前用户没有配置打印机,请先配置");
        return;
      }
      var reg = /^[0-9a-zA-Z]+$/; // 验证0-9的任意数字最少出现1次。
      if (!this.printOrderNo) {
        this.$message.error("请录入订单号");
        return;
      }
      if (
        this.printOrderNo.indexOf(",") > -1 ||
        this.printOrderNo.indexOf("，") > -1
      ) {
        this.$message.error("多个订单号换行隔开,不含逗号");
        return;
      }
      var waybillArray = this.printOrderNo.split("\n");
      var waybillList = new Array();
      for (var n = 0; n < waybillArray.length; n++) {
        if (waybillArray[n]) {
          if (reg.test(waybillArray[n])) {
            if (waybillList.indexOf(waybillArray[n]) > -1) {
              this.$message.error({
                msg: "订单号【" + waybillArray[n] + "】重复"
              });
              return;
            } else {
              waybillList.push(waybillArray[n]);
            }
          } else {
            this.$message.error("订单号输入有误");
            return;
          }
        }
      }
      ajax("batchPrintGreenBoxLabel", { waybillList: waybillList }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
          }
        },
        error => {
          console.log(error);
        }
      );
    }
  }
};
</script>
<style></style>
